package requests

import (
	"errors"
	"fmt"
	"goblog/app/models/user"
	"goblog/pkg/model"
	"strings"

	"github.com/thedevsaddam/govalidator"
)

func init() {
	govalidator.AddCustomRule("not_exists", func(field, rule, message string, value interface{}) error {
		rng := strings.Split(strings.TrimPrefix(rule, "not_exists:"), ",")
		tableName := rng[0]
		dbField := rng[1]
		val := value.(string)

		var count int64
		model.DB.Table(tableName).Where(dbField+" = ?", val).Count(&count)
		if count != 0 {
			if message != "" {
				return errors.New(message)
			}
			return fmt.Errorf("%v 已被占用", val)
		}
		return nil
	})
}

func ValidateRegisterForm(data user.User) map[string][]string {
	rules := govalidator.MapData{
		"name":             []string{"required", "alpha_num", "between:3,20", "not_exists:users,name"},
		"email":            []string{"required", "min:4", "max:30", "email", "not_exists:users,email"},
		"password":         []string{"required", "min:6"},
		"password_confirm": []string{"required"},
	}

	message := govalidator.MapData{
		"name": []string{
			"required:用户名必填",
			"alpha_num:用户名格式错误，只支持数字和英文",
			"between:用户名长度需在3~20个字符",
		},
		"email": []string{
			"required:邮箱必填",
			"min:邮箱长度需大于4",
			"max:邮箱长度需小于30",
			"email:邮箱格式不正确",
		},
		"password": []string{
			"required:密码必填",
			"min:密码长度需大于6",
		},
		"password_confirm": []string{
			"required:确认密码必填",
		},
	}

	opts := govalidator.Options{
		Data:          &data,
		Rules:         rules,
		Messages:      message,
		TagIdentifier: "valid",
	}

	errs := govalidator.New(opts).ValidateStruct()

	if data.Password != data.PasswordConfirm {
		errs["password_confirm"] = append(errs["password_confirm"], "两次输入密码不匹配")
	}
	return errs
}
